<template>
  <div class="dashboard-container">
    <!-- 关键指标卡片 -->
    <!-- <el-row :gutter="16" class="metrics-row">
      <el-col :span="6">
        <el-card class="metric-card campus-metric" shadow="hover">
          <div class="metric-content">
            <div class="metric-icon">
              <i class="el-icon-office-building" />
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ totalMetrics.totalCampus }}</div>
              <div class="metric-label">校区总数</div>
              <div class="metric-rate" :class="{ positive: totalMetrics.campusGrowthRate >= 0 }">
                <i :class="totalMetrics.campusGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(totalMetrics.campusGrowthRate) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card investment-metric" shadow="hover">
          <div class="metric-content">
            <div class="metric-icon">
              <i class="el-icon-s-cooperation" />
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ totalMetrics.totalInvestment }}</div>
              <div class="metric-label">招商签约</div>
              <div class="metric-rate" :class="{ positive: totalMetrics.investmentGrowthRate >= 0 }">
                <i :class="totalMetrics.investmentGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(totalMetrics.investmentGrowthRate) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card guidance-metric" shadow="hover">
          <div class="metric-content">
            <div class="metric-icon">
              <i class="el-icon-s-help" />
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ totalMetrics.totalGuidance }}</div>
              <div class="metric-label">开业辅导</div>
              <div class="metric-rate" :class="{ positive: totalMetrics.guidanceGrowthRate >= 0 }">
                <i :class="totalMetrics.guidanceGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(totalMetrics.guidanceGrowthRate) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card renewal-metric" shadow="hover">
          <div class="metric-content">
            <div class="metric-icon">
              <i class="el-icon-s-finance" />
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ totalMetrics.renewalRate }}%</div>
              <div class="metric-label">续费率</div>
              <div class="metric-rate" :class="{ positive: totalMetrics.renewalGrowthRate >= 0 }">
                <i :class="totalMetrics.renewalGrowthRate >= 0 ? 'el-icon-top' : 'el-icon-bottom'" />
                {{ Math.abs(totalMetrics.renewalGrowthRate) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row> -->

    <!-- 数据看板主体 -->
    <div class="dashboard-main">
      <!-- 校区状态数据模块 -->
      <CampusStatusReport :management-area-options="managementAreaOptions" :status-options="campusStatusOptions" :brand-options="brandOptions" />

      <!-- 校区签约统计和服务统计模块 - 左右布局 -->
      <el-row :gutter="16" class="statistics-row">
        <el-col :span="12">
          <ContractStatisticsReport :management-area-options="managementAreaOptions" :brand-options="brandOptions" />
        </el-col>
        <el-col :span="12">
          <ServiceStatisticsReport :management-area-options="managementAreaOptions" :brand-options="brandOptions" />
        </el-col>
      </el-row> 
      <!-- 校区续费统计模块 -->
      <RenewalStatisticsReport :management-area-options="managementAreaOptions" :brand-options="brandOptions" />

      <!-- 校区参训统计模块 -->
      <TrainingStatisticsReport :management-area-options="managementAreaOptions" :brand-options="brandOptions" :certificate-template-options="certificateTemplateOptions" />
    </div>
  </div>
</template>

<script>
// 导入报表组件
import CampusStatusReport from '../components/CampusStatusReport.vue'
import ContractStatisticsReport from '../components/ContractStatisticsReport.vue'
import ServiceStatisticsReport from '../components/ServiceStatisticsReport.vue'
import GuidanceStatisticsReport from '../components/GuidanceStatisticsReport.vue'
import RenewalStatisticsReport from '../components/RenewalStatisticsReport.vue'
import TrainingStatisticsReport from '../components/TrainingStatisticsReport.vue'

export default {
  name: 'CampusOperationDashboard',
  components: {
    CampusStatusReport,
    ContractStatisticsReport,
    ServiceStatisticsReport,
    GuidanceStatisticsReport,
    RenewalStatisticsReport,
    TrainingStatisticsReport
  },
  data() {
    return {
      // 全局加载状态
      globalLoading: false,

      // 管理区域选项
      managementAreaOptions: [],
      // 校区状态选项
      campusStatusOptions: [],
      // 品牌选项
      brandOptions: [],
      // 证书类型选项
      certificateTemplateOptions: [],

      // 关键指标数据（各组件内部独立管理，此处仅用于展示默认值）
      totalMetrics: {
        totalCampus: 0,
        campusGrowthRate: 0,
        totalInvestment: 0,
        investmentGrowthRate: 0,
        totalGuidance: 0,
        guidanceGrowthRate: 0,
        renewalRate: 0,
        renewalGrowthRate: 0
      }
    }
  },

  async mounted() {
    // 先加载基础数据
    await this.loadManagementAreas()
    await this.loadCampusStatus()
    await this.loadBrandOptions()
    await this.loadTrainOptions()
  },

  methods: {
    // 获取当前年度时间范围
    getCurrentYearRange() {
      const currentYear = new Date().getFullYear()
      const startDate = `${currentYear}-01-01`
      const endDate = `${currentYear}-12-31`
      return [startDate, endDate]
    },

    // 加载管理区域数据字典
    async loadManagementAreas() {
      try {
        // 使用标准的数据字典调用方式
        const res = await this.$store.dispatch('base/getDictionaryData', {
          sort: 'MANAGEMENT_AREA'
        })

        // 调试：输出从store获取的原始数据
        console.log('=== index.vue loadManagementAreas 调试信息 ===')
        console.log('从store获取的原始数据:', JSON.stringify(res, null, 2))
        console.log('原始数据数量:', res.length)

        // 检查每个原始数据项的字段
        res.forEach((item, index) => {
          console.log(`原始数据项 ${index}:`, {
            fullName: item.fullName,
            enCode: item.enCode,
            sortCode: item.sortCode,
            sortCodeType: typeof item.sortCode,
            enabledMark: item.enabledMark
          })
        })

        // 按sortCode字段进行升序排序 - 强制类型转换
        this.managementAreaOptions = res.sort((a, b) => {
          const aSortCode = Number(a.sortCode || 999)
          const bSortCode = Number(b.sortCode || 999)
          console.log(`index.vue 排序比较: ${a.fullName}(${a.sortCode}->${aSortCode}) vs ${b.fullName}(${b.sortCode}->${bSortCode})`)
          return aSortCode - bSortCode
        })

        console.log('排序后的数据:', JSON.stringify(this.managementAreaOptions, null, 2))
        console.log('=== index.vue loadManagementAreas 调试信息结束 ===')
      } catch (error) {
        console.error('加载管理区域数据字典失败:', error)
        this.$message.error('加载管理区域选项失败')
      }
    },

    // 加载校区状态数据字典
    async loadCampusStatus() {
      try {
        // 使用标准的数据字典调用方式
        const res = await this.$store.dispatch('base/getDictionaryData', {
          sort: 'CampusStatus'
        })
        // 按sortCode字段进行升序排序
        this.campusStatusOptions = res.sort((a, b) => (a.sortCode || 0) - (b.sortCode || 0))
      } catch (error) {
        console.error('加载校区状态数据字典失败:', error)
        this.$message.error('加载校区状态选项失败')
      }
    },

    // 加载品牌数据字典
    async loadBrandOptions() {
      try {
        // 使用标准的数据字典调用方式
        const res = await this.$store.dispatch('base/getDictionaryData', {
          sort: 'Brand'
        })
        // 按sortCode字段进行升序排序，只显示启用的品牌
        this.brandOptions = res.sort((a, b) => (a.sortCode || 0) - (b.sortCode || 0))
      } catch (error) {
        console.error('加载品牌数据字典失败:', error)
        this.$message.error('加载品牌选项失败')
      }
    },

    // 加载培训选项（证书模版类型）
    async loadTrainOptions() {
      try {
        // 使用标准的数据字典调用方式 - 证书模版类型对应师训项目实体类的证书模版字段
        const res = await this.$store.dispatch('base/getDictionaryData', {
          sort: 'TrainCertificateType'
        })
        // 按sortCode字段进行升序排序，只显示启用的证书模版类型
        this.certificateTemplateOptions = res.sort((a, b) => (a.sortCode || 0) - (b.sortCode || 0))
      } catch (error) {
        console.error('加载证书模版数据字典失败:', error)
        this.$message.error('加载师训证书模版选项失败')
      }
    }
  }
}
</script>

<style scoped>
/* ===== CSS变量定义 ===== */
:root {
  --border-radius-base: 12px;
  --border-radius-large: 16px;
  --spacing-small: 12px;
  --spacing-base: 16px;
  --spacing-large: 24px;
  --font-size-small: 12px;
  --font-size-base: 14px;
  --font-size-large: 32px;
  --font-size-icon: 48px;
  --transition-base: 0.2s;
  --shadow-base: 0 8px 32px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* ===== 基础卡片样式 ===== */
.base-card {
  border: none;
  border-radius: var(--border-radius-base);
  color: white;
  transition: transform var(--transition-base);
}

.base-card:hover {
  transform: translateY(-2px);
}

/* ===== 渐变主题样式 ===== */
.gradient-theme-purple {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.gradient-theme-pink {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.gradient-theme-blue {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.gradient-theme-green {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

/* ===== 关键指标卡片样式 ===== */
.metrics-row {
  margin-bottom: var(--spacing-large);
}

.metric-card {
  border: none;
  border-radius: var(--border-radius-base);
  color: white;
  transition: transform var(--transition-base);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* 默认主题 */
}

.metric-card:hover {
  transform: translateY(-2px);
}

.metric-card.campus-metric {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.metric-card.investment-metric {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.metric-card.guidance-metric {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.metric-card.renewal-metric {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

/* ===== 指标内容布局 ===== */
.metric-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.metric-icon {
  font-size: var(--font-size-icon);
  margin-right: var(--spacing-base);
  opacity: 0.8;
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: var(--font-size-large);
  font-weight: 700;
  margin: 0 0 8px 0;
}

.metric-label {
  font-size: var(--font-size-base);
  opacity: 0.9;
  margin: 0 0 8px 0;
}

.metric-rate {
  font-size: var(--font-size-small);
  display: flex;
  align-items: center;
  gap: 4px;
  opacity: 0.8;
}

.metric-rate.positive {
  color: #a7f3d0;
}

.metric-rate.negative {
  color: #fecaca;
}

/* ===== 数据看板主体样式 ===== */
.dashboard-main {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-base);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: var(--border-radius-large);
  padding: var(--spacing-large);
  box-shadow: var(--shadow-base);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 1;
}

/* 看板背景装饰效果 */
.dashboard-main::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent 0%, rgba(102, 126, 234, 0.02) 50%, transparent 100%), repeating-linear-gradient(45deg, transparent, transparent 20px, rgba(102, 126, 234, 0.01) 20px, rgba(102, 126, 234, 0.01) 40px);
  border-radius: var(--border-radius-large);
  pointer-events: none;
  z-index: -1;
}

/* ===== 统计组件行样式 ===== */
.statistics-row {
  margin-bottom: var(--spacing-base);
}

.statistics-row .el-col {
  height: 100%;
}

/* ===== 响应式设计 ===== */
@media (max-width: 768px) {
  .dashboard-container {
    padding: var(--spacing-small);
  }

  .dashboard-main {
    padding: var(--spacing-base);
    border-radius: var(--border-radius-base);
  }

  .metric-value {
    font-size: 24px;
  }

  .metric-content {
    padding: var(--spacing-base);
  }

  .metric-icon {
    font-size: 36px;
    margin-right: var(--spacing-small);
  }
}

/* ===== 通用工具类 ===== */
.glass-effect {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.hover-lift {
  transition: transform var(--transition-base);
}

.hover-lift:hover {
  transform: translateY(-2px);
}

.flex-center {
  display: flex;
  align-items: center;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
